package 回溯;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TTDB
 * @create 2025/9/18
 */
public class generateParenthesis {
    public List<String> generateParenthesis(int n) {
        if (n == 0) return new ArrayList<>();
        List<String> res = new ArrayList<>();
        dfs(res, "", n, n);
        return res;
    }

    public void dfs(List<String> res, String path, int left, int right) {
        if (left == 0 && right == 0) {
            res.add(path);
            return;
        }
        if (left > right) return;
        //注意顺序，先放左再放右，否则会出错
        if (left > 0) {
            dfs(res, path + "(", left - 1, right);
        }
        if (right > 0) {
            dfs(res, path + ")", left, right - 1);
        }
    }
}
